package cn.com.shaom.learning.sb.security.example2.service;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;

/**
 * ClassName: CumPermissionEvaluator
 * Description: 自定义的 PermissionEvaluator
 * Date: 2017/12/28 10:23 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
public class CumPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {

        System.out.println("1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

        if ((authentication == null) || (targetDomainObject == null) || !(permission instanceof String)) {
            return false;
        }

        return hasPrivilege(authentication, targetDomainObject.toString(), permission.toString().toUpperCase());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {

        System.out.println("2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

        if ((authentication == null) || (targetType == null) || !(permission instanceof String)) {
            return false;
        }
        return hasPrivilege(authentication, targetType.toUpperCase(),
                permission.toString().toUpperCase());
    }

    /**
     * 这边的实现随便写的
     *
     * @param auth
     * @param targetType
     * @param permission
     * @return
     */
    private boolean hasPrivilege(Authentication auth, String targetType, String permission) {
        for (GrantedAuthority grantedAuth : auth.getAuthorities()) {
            String authority = grantedAuth.getAuthority();
            // 这边随便写的
            if (authority.equals(targetType)) {
                if (authority.equals(permission)) {
                    return true;
                }
            }
        }
        return false;
    }
}
